<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Message;
use Illuminate\Support\Facades\DB;
use Overtrue\EasySms\EasySms;
use Illuminate\Support\Facades\Config;
use Validator;
use Overtrue\EasySms\Exceptions\NoGatewayAvailableException;
use Illuminate\Support\Facades\Log;
use App\Models\User;


class MessageController extends Controller
{
    private $company_id;
    private $user;
    private $role_flag;
    public function __construct()
    {
        $this->deviceType = $this->getDevice();
        if (\Auth::guard('api')->check()) {
            $user = \Auth::guard('api')->user();
            $data = User::find($user->id);
            if($this->deviceType){
//                PC
                $this->company_id = $data->company_id;
                $this->user = $data;
            }else{
//                APP
                $this->company_id = $data->appcompany_id;
                $this->user = $data;
                $this->user->company_id = $data->appcompany_id;
            }
            $company = \App\Models\Company::find($this->user->company_id);
            if(!empty($company)){
                $this->role_flag = $company->role_flag;
            }
        }
    }
    /**
     * 通讯录
     * @param  $uid     [用户ID]
     * @return $请求返回结果(json)
     */
    public function messageList(Request $request){
//        $validator = Validator::make($id, Message::$rules,Message::$message);
//        if ($validator->fails()) {
//            return response()->json(['code' => 400, 'msg' => $validator->errors()->first(),'data'=>'']);
//        }
        $uid = $request->input('uid');
        $name = '%'.$request->input('name').'%';
        $type = $request->input('type');
        if(empty($uid) || is_int($uid)){
            return response()->json(['code' => 400, 'msg' =>"非法操作",'data'=>'']);
        }
//        $userInfo = DB::table('users')->where('id',$uid)->first();
        $userInfo = $this->user;
        if($type == 1){
            $list = DB::table('staff')
                ->leftjoin('users', 'staff.mobile', '=', 'users.mobile')
                ->select('staff.id','users.id as uid','staff.company_id as cid','users.image','users.accid','staff.name','staff.mobile')
                ->where(['staff.company_id'=>$userInfo->company_id,'staff.status'=>0])
                ->whereNotIn('staff.mobile', [$userInfo->mobile])
                ->get();
        }
        if($type == 2){
            $list = DB::table('staff')
                ->leftjoin('users', 'staff.mobile', '=', 'users.mobile')
                ->select('staff.id','users.id as uid','staff.company_id as cid','users.image','users.accid','staff.name','staff.mobile')
                ->where([['staff.company_id',$userInfo->company_id],['staff.name','like',$name],['staff.status',0]])
                ->whereNotIn('staff.mobile', [$userInfo->mobile])
                ->get();
        }
        $use = $this->user;
        foreach($list as $k=>$v){
//            if( !is_null($v->uid)){
//                $info= DB::table('users')->where('id',$v->uid)->first();
//                if($info->company_id != $use->company_id){
//                    $v->uid = 0;
//                }
//            }
            if(is_null($v->uid)) $v->uid=0;
            if(is_null($v->image)) $v->image="";
            if(is_null($v->accid)) $v->accid="";
        }
        return response()->json(['code' => 200, 'msg' =>"请求成功",'data'=>['list'=>$list]]);
    }
    /**
     * 发送邀请短信
     * @param  $mobile     [用户ID]
     * @return $请求返回结果(json)
     */
    public function sendInvitations(Request $request){
        $userInfo = $this->user;
        $validator = Validator::make($request->all(), Message::$rules,Message::$message);
        if ($validator->fails()) {
            return response()->json(['code' => 400, 'msg' => $validator->errors()->first(),'data'=>'']);
        }
        $mobile = $request->input('mobile');
        $cmpInfo = DB::table('companies')->where('id',$userInfo->company_id)->first();
        $config = Config::get('info.message_config');
        $easySms = new EasySms($config);
       
        try{
            $result = $easySms->send($mobile, [
                'content' => '您的同事${user}邀请您加入“${company}”，请联系管理员下载软件并加入团队。',
                'template' => 'SMS_133975442',
                'data' => [
                    'user' => $userInfo->name,
                    'company' => $cmpInfo->name,
                ],
            ]);
        }catch(NoGatewayAvailableException $e){
            return  response()->json(['code'=>400,'msg'=>'邀请失败','data'=>'']);
        }
        if($result['aliyun']['status']=='success'){
            return  response()->json(['code'=>200,'msg'=>'短信发送成功','data'=>'']);
        }else{
            return  response()->json(['code'=>400,'msg'=>'邀请失败','data'=>'']);
        }
    }
   
    /**
     * 创建群
     *
     *  @param  $member    [群成员]
     *  @param  $from    [1手动,2系统]
     * @return $请求返回结果(json)
     */
    public function createTeam(Request $request){
        $userInfo = \Auth::guard('api')->user();
        if(empty($userInfo)){
            return  response()->json(['code'=>400,'msg'=>'用户未登录','data'=>'']);
        }
        $data = $request->all();
        $groupMember = json_decode($data['member'],true);
        $from = $data['from'];
        $i = 0;
        $groupName = '';
        //群名称拼装
        foreach($groupMember as $k){
              $memberInfo =  DB::table('users')->where('id',$k)->first();
             if(empty($memberInfo)){
                 return  response()->json(['code'=>400,'msg'=>'群创建失败','data'=>'']);
             }
              $memberList[]=$memberInfo->accid;
            if($i<2) {
                $groupName .= ','.$memberInfo->name;
            };
            $i++;
        }
        $i = $i+1;
        $groupName = $userInfo->name.$groupName.'...'.'('.$i.'人)';
        $p = $this->initialize();
        if($from == 1){
            $isOff = 1;
        }else{
            $isOff = 0;
        }
        $result = $p->createGroup($groupName,$userInfo->accid,$memberList,'','','invite',$isOff,'0','');
        if($result['code'] == 200){
            //群信息
            DB::table('team')->insert([
                ['company_id' => $userInfo->company_id, 'user_id' => $userInfo->id,'team_id' => $result['tid'],'type'=>$from,'created_at'=>time(),'updated_at'=>time()]
            ]);
//            //群成员信息
//            foreach($memberList as $k){
//
//            }
            return  response()->json(['code'=>200,'msg'=>'群创建成功','data'=>['tid'=>$result['tid']]]);
        }else{
            return  response()->json(['code'=>400,'msg'=>'群创建失败','data'=>'']);
        }
    }
    /**
     * 拉人
     * @param  $tid   [群ID]
     * @param  $owner   [群主ID]
     *  @param  $member    [成员ID]
     *  @param  $from    [1手动,2系统]
     * @return $请求返回结果(json)
     */
    public function add(Request $request){
        $data = $request->all();
        $tid = $data['tid'];
        $owner = $data['owner'];
        $member = $data['member'];
        $from = $data['from'];
        $p = $this->initialize();
        if($from == 2){
            $isOff = 0;
        }else{
            $isOff = 1;
        }
        $result =  $p->addIntoGroup($tid,$owner,$member,$isOff);
        if($result['code'] == 200){
            return  response()->json(['code'=>200,'msg'=>'邀请成功','data'=>'']);
        }else{
            return  response()->json(['code'=>200,'msg'=>'邀请失败','data'=>'']);
        }
    }
    /**
     * 踢人
     * @param  $tid   [群ID]
     *  @param  $member    [成员ID]
     *  @param  $from    [1手动,2系统]
     * @return $请求返回结果(json)
     */
    public function kick(Request $request){
        $data = $request->all();
        $tid = $data['tid'];
        $owner = $data['owner'];
        $member = $data['member'];
        $p = $this->initialize();
        $result = $p->kickFromGroup($tid,$owner,$member);
        if($result['code'] == 200){
            return  response()->json(['code'=>200,'msg'=>'操作成功','data'=>'']);
        }else{
            return  response()->json(['code'=>400,'msg'=>'操作失败','data'=>'']);
        }
    }
    /**
     * 解散群
     * @param  $tid   [群ID]
     *  @param  $owner    [群主ACCID]
     * @return $请求返回结果(json)
     */
    public function remove(Request $request){
        $data = $request->all();
        $tid = $data['tid'];
        $owner  = $data['owner'];
        $p = $this->initialize();
        $result = $p->removeGroup($tid,$owner);
        if($result['code'] == 200){
//            删除team
            return  response()->json(['code'=>200,'msg'=>'操作成功','data'=>'']);
        }else{
            return  response()->json(['code'=>400,'msg'=>'操作失败','data'=>'']);
        }
    }
    
    /**
     * 修改群名称
     * @param  $tid   [群ID]
     * @param  $owner    [群主ACCID]
     * @param  $tname    [群名]
     * @return $请求返回结果(json)
     */
    public function upTeamNick(Request $request){
        $data = $request->all();
        $tid = $data['tid'];
        $owner = $data['owner'];
        $tname = $data['tname'];
        $p = $this->initialize();
        $result = $p->updateGroup($tid,$owner,$tname);
        if($result['code'] == 200){
            return  response()->json(['code'=>200,'msg'=>'操作成功','data'=>'']);
        }else{
            return  response()->json(['code'=>400,'msg'=>'操作失败','data'=>'']);
        }
    }
    /**
     * 退出群
     * @param  $tid   [群ID]
     * @param  $owner    [群主ACCID]
     * @param  $tname    [群名]
     * @return $请求返回结果(json)
     */
    public function leave(Request $request){
        $data = $request->all();
        $tid = $data['tid'];
        $accid = $data['accid'];
        $p = $this->initialize();
        $result  = $p->leave($tid,$accid);
        if($result['code'] == 200){
            return  response()->json(['code'=>200,'msg'=>'操作成功','data'=>'']);
        }else{
            return  response()->json(['code'=>400,'msg'=>'操作失败','data'=>'']);
        }
    }
    /**
     * 群通知消息
     * @param  $tid   [群ID]
     * @param  $owner    [群主ACCID]
     * @param  $tname    [群名]
     * @return $请求返回结果(json)
     */
    public function sendMsg(Request $request){
        $userInfo = \Auth::guard('api')->user();
        $content = array('msg'=>$request->input('content'));
        $tid = $request->input('tid');
        $cmpInfo = DB::table('companies')->where('id',$userInfo->company_id)->first();
        $p = $this->initialize();
        $result = $p->sendMsg($cmpInfo->interview_assistant,1,$tid,0,$content);
        if($result['code'] == 200){
            DB::table('interview_assistant')->insert([
                ['company_id' => $userInfo->company_id, 'send_id' =>$userInfo->company_id,'receive_id' => $tid,'type'=>7,'from'=>3,'content'=>json_encode($content),'created_at'=>time(),'updated_at'=>time()]
            ]);
            return  response()->json(['code'=>200,'msg'=>'操作成功','data'=>'']);
        }else{
            return  response()->json(['code'=>400,'msg'=>'操作失败','data'=>'']);
        }
    }
    /**
     * 群通知
     * @param  $flowId   [历史流程ID]
     * @return $请求返回结果(json)
     */
    public function teamNotice(Request $request){
        $flowId = $request->input('id');
        $historyInfo = DB::table('flow_histories')->where('id',$flowId)->first();
        $resumeInfo = DB::table('resumes')->where('id',$historyInfo->resume_id)->first();
        if($historyInfo->check_status == 1){
            $content = $historyInfo->admin_name.'完成了'.$resumeInfo->name.'的'.$historyInfo->step_name.'的评价(通过)';
        }else if($historyInfo->check_status == 2){
            $content = $historyInfo->admin_name.'完成了'.$resumeInfo->name.'的'.$historyInfo->step_name.'的评价(未通过)';
        }else{
            $content = $historyInfo->admin_name.'完成了'.$resumeInfo->name.'的'.$historyInfo->step_name.'的评价(待定)';
        }
        return  response()->json(['code'=>200,'msg'=>'操作成功','data'=>['content'=>$content,'tid'=>(string)$resumeInfo->team_id]]);
    }
    /**
     * 简历详情
     * @param  $tid   [群ID]
     * @return $请求返回结果(json)
     */
    public function resumeInfo(Request $request){
        $tid = $request->input('tid');
        $teamInfo = DB::table('team')->where('team_id',$tid)->first();
        if(empty($teamInfo)){
            return  response()->json(['code'=>400,'msg'=>'非群组','data'=>'']);
        }
        $resumeInfo = DB::table('resumes')->where('id',$teamInfo->resume_id)->select('id as resumeId','name','image as img','position','company_name as cmpName','step_name as stepName','job_date as jobDate')->first();
        if(empty($resumeInfo)){
            $resumeInfo = [];
        }
        return  response()->json(['code'=>200,'msg'=>'操作成功','data'=>['content'=>$resumeInfo]]);
    }
    /**
     * 面试通知
     * @param  $id   [历史流程ID]
     * @return $请求返回结果(json)
     */
    public function interviewMsg(Request $request){
        $id = $request->input('id');
        $info = DB::table('flow_histories')->where('id',$id)->first();
        $hrInfo =DB::table('users')->where('id',$info->owner_id)->first();
        $interviewInfo = DB::table('users')->where('id',$info->admin_id)->first();
        $resumeInfo = DB::table('resumes')->where('id',$info->resume_id)->first();
        $cmpInfo = DB::table('companies')->where('id',$info->company_id)->first();
        $p = $this->initialize();
        $time = time();
        if(empty($resumeInfo->team_id)){
            //创建群将hr面试官拉进群
            $memberList[] = $hrInfo->accid;
            $memberList[] = $interviewInfo->accid;
            $member[] =$hrInfo;
            $member[] = $interviewInfo;
            $groupName =$resumeInfo->name.'面试群' ;
            $result = $p->createGroup($groupName,$cmpInfo->interview_assistant,$memberList,'','','invite','0','0','');
            if($result['code'] == 200){
                //群信息
                DB::table('team')->insert([
                    ['company_id' => $info->company_id, 'user_id' => 0,'team_id' => $result['tid'],'type'=>2,'resume_id'=>$info->resume_id,'created_at'=>time(),'updated_at'=>time()]
                ]);
                //群主信息
                DB::table('team_member')->insert(['company_id'=>$info->company_id,'user_id'=>0,'acc_id'=>$cmpInfo->interview_assistant,'team_id'=>$result['tid'],'is_owner'=>1,'created_at'=>$time,'updated_at'=>$time]);
                //群成员信息
                foreach($member as $k){
                    DB::table('team_member')->insert(['company_id'=>$info->company_id,'user_id'=>$k->id,'acc_id'=>$k->accid,'team_id'=>$result['tid'],'is_owner'=>0,'created_at'=>$time,'updated_at'=>$time]);
                }
                DB::table('resumes')->where('id',$info->resume_id)->update(['team_id'=>$result['tid'],'updated_at'=>$time]);
            }else{
                return  response()->json(['code'=>400,'msg'=>'操作失败','data'=>'']);
            }
        }else{
            $tid = $resumeInfo->team_id;
            $owner = $cmpInfo->interview_assistant;
            $member=[$interviewInfo->accid];
            $result =  $p->addIntoGroup($tid,$owner,$member);
            if($result['code'] == 200){
                DB::table('team_member')->insert(['company_id'=>$info->company_id,'user_id'=>$interviewInfo->id,'acc_id'=>$interviewInfo->accid,'team_id'=>$tid,'is_owner'=>0,'created_at'=>$time,'updated_at'=>$time]);
            }else if($result['code'] != 801){
                return  response()->json(['code'=>400,'msg'=>'操作失败','data'=>'']);
            }
        }
            $from  = 'momevipinterview';
            $to = $interviewInfo->accid;
            $msgId= DB::table('interview_assistant')->insertGetId(['company_id'=>$info->company_id,'send_id'=>$info->company_id,'receive_id'=>$interviewInfo->id,'type'=>3,'from'=>2,'content'=>'fail','created_at'=>$time,'updated_at'=>$time]);
            $content =[
                'data'=>[
                    'type'=>2,
                    'msgId'=>$msgId,
                    'header'=>$resumeInfo->name.'的面试通知',
                    'info'=>[
                        'name'=>$resumeInfo->name,
                        'img'=>$resumeInfo->image,
                        'position'=>$resumeInfo->position,
                        'cmpName'=>$resumeInfo->company_name,
                        'stepName'=>$resumeInfo->step_name,
                        'jobDate'=>$resumeInfo->job_date,
                        'address'=>$info->address,
                        'intervierName'=> $interviewInfo->name,
                        'stime'=>$info->stime,
                        'etime'=>$info->etime,
                        'resumeId'=>$resumeInfo->id ,
                        'msgId'=>$msgId,
                        'hrId'=>$hrInfo->id,
                        'flowId'=>$id
                    ]
                ]
            ];
            $pushContent = $hrInfo->name.'邀请您参加'.$resumeInfo->name.'的面试';
            $result = $p->sendMsg($from,0,$to,'100',$content,array("push"=>true,"roam"=>true,"history"=>true,"sendersync"=>true, "route"=>false,'needPushNick'=>true),$pushContent);
           if($result['code'] == 200){
               
               DB::table('interview_assistant')->where('id',$msgId)->update(['content'=>json_encode($content),'updated_at'=>$time]);
           }
            return  response()->json(['code'=>200,'msg'=>'操作成功','data'=>'']);
    }

    /**
     * 面试通知处理
     * @param  $msgId   [消息ID]
     *  @param  $flowId   [历史流程ID]
     * @param  $type    [1:同意；2:不同意]
     * @param  $reasion    [原因]
     * @return $请求返回结果(json)
     */
    public function interviewmsgDeal(Request $request){
        $userInfo = $this->user;
        $msgId = $request->input('msgId');
        $flowId = $request->input('flowId');
        $type = $request->input('type');
        $reasion = $request->input('reasion') ?? "";
//
        if($type == 1){
            $infoId =  $flowId;
            $uid = $userInfo->id;
            $timeInfo = DB::table('flow_histories')
                ->where('id',$infoId)
                ->first();
            $calInfo = DB::table('calendar')
                ->where([['info_id','=',$infoId],
                    ['owner_id','=',$uid]])
                ->first();
            if(empty($calInfo)){
                $timeConflict = DB::select('select * FROM  calendar where NOT (end_time < ? or start_time > ?) and owner_id = ?',[$timeInfo->stime,$timeInfo->etime,$uid]);
                Log::info('11'."@".$uid);
                if(!empty($timeConflict)){
                    return  response()->json(['code'=>400,'msg'=>'时间冲突,日历添加失败','data'=>'']);
                }
                $reumes = DB::table('resumes')->where('id',$timeInfo->resume_id)->first();
                $result = DB::table('calendar')->insert(
                    [   'info_id' => $infoId,
                        'owner_id'=>$uid,
                        'resume_id'=>$timeInfo->resume_id,
                        'name'=>$reumes->name,
                        'position'=>$reumes->position,
                        'step_name'=>$timeInfo->step_name,
                        'address'=>$timeInfo->address,
                        'interview_name'=>$timeInfo->owner_name,
                        'start_time' =>$timeInfo->stime,
                        'end_time'=>$timeInfo->etime,
                        'created_at'=>time(),
                        'updated_at'=>time()]
                );
            }else{
                if($uid == $calInfo->owner_id){
                    $timeConflict = DB::select('select * FROM  calendar where NOT  (end_time < ? or start_time > ?) and owner_id = ?',[$timeInfo->stime,$timeInfo->etime,$uid]);
                    Log::info('22'."@".$uid);
                    if(!empty($timeConflict)){
                        return  response()->json(['code'=>400,'msg'=>'时间冲突,日历添加失败','data'=>'']);
                    }
                    $result =  DB::table('calendar')
                        ->where('info_id',  $infoId)
                        ->update(['start_time' => $timeInfo->stime,
                            'end_time'=>$timeInfo->etime,'updated_at'=>time()]);
                }else{
                    $reumes = DB::table('resumes')->where('id',$timeInfo->resume_id)->first();
                    $timeConflict = DB::select('select * FROM  calendar where NOT  (end_time < ? or start_time > ?) and owner_id = ?',[$timeInfo->stime,$timeInfo->etime,$uid]);
                    Log::info('33'."@".$uid);
                    if(!empty($timeConflict)){
                        return  response()->json(['code'=>400,'msg'=>'时间冲突,日历添加失败','data'=>'']);
                    }
                    $result = DB::table('calendar')->insert(
                        [   'info_id' => $infoId,
                            'owner_id'=>$uid,
                            'resume_id'=>$timeInfo->resume_id,
                            'name'=>$reumes->name,
                            'position'=>$reumes->position,
                            'step_name'=>$timeInfo->step_name,
                            'address'=>$timeInfo->address,
                            'interview_name'=>$timeInfo->owner_name,
                            'start_time' =>$timeInfo->stime,
                            'end_time'=>$timeInfo->etime,
                            'created_at'=>time(),
                            'updated_at'=>time()]
                    );
                }
            }
            if(!$result){
                return  response()->json(['code'=>400,'msg'=>'日程创建失败','data'=>'']);
            }
        }
//
        $msgInfo = DB::table('interview_assistant')->where('id',$msgId)->first();
        $flowInfo = DB::table('flow_histories')->where('id',$flowId)->first();
        $hrInfo = DB::table('users')->where('id',$flowInfo->owner_id)->first();
        $content = json_decode($msgInfo->content,true);
        $time = time();
        $from  = 'momevipinterview';
        $to =  $hrInfo->accid;
        $p = $this->initialize();
        if($type==1){
            $res = '同意了';
        }else{
            $res = "拒绝了";
        }
        $pushContent = $flowInfo->admin_name.$res.$content['data']['info']['name'].'的面试';
        $result = $p->sendMsg($from,0,$to,'100',$content,array("push"=>true,"roam"=>true,"history"=>true,"sendersync"=>true, "route"=>false,'needPushNick'=>true),$pushContent);
        if($result['code'] == 200){
            DB::table('interview_assistant')
                ->insertGetId(['company_id'=>$userInfo->company_id,'send_id'=>$userInfo->company_id,'receive_id'=>$flowInfo->owner_id,'type'=>4,'from'=>2,'status'=>$type,'content'=>json_encode($content),'reasion'=>$reasion,'created_at'=>$time,'updated_at'=>$time]);
            DB::table('interview_assistant')
                ->where('id',$msgId)->update(['status'=>$type,'reasion'=>$reasion,'updated_at'=>$time]);
            return  response()->json(['code'=>200,'msg'=>'操作成功','data'=>'']);
        }else{
            return  response()->json(['code'=>400,'msg'=>'操作失败','data'=>'']);
        }
    }
    /**
     * 申请简历权限
     * @param  $id  [简历ID]
     * @param  $reasion    [理由]
     * @return $请求返回结果(json)
     */
    public function applyControl(Request $request){
        $userInfo = $this->user;
        $id = $request->input('id');
        $reasion = $request->input('reasion') ?? "";
        $time = time();
        $resumeInfo = DB::table('resumes')->where('id',$id)->first();
        if(empty($resumeInfo)){
         return    response()->json(['code'=>400,'msg'=>'简历不存在','data'=>'']);
        }
        $ownerInfo = DB::table('users')->where('id',$resumeInfo->owner_id)->first();
        //向简历所有人发送自定义消息
        $p = $this->initialize();
        $from  = 'momevipinterview';
        $to = $ownerInfo->accid;
       $msgInfo =  DB::table('interview_assistant')->where(['company_id'=>$userInfo->company_id,'send_id'=>$userInfo->id,'receive_id'=>$ownerInfo->id,'type'=>1,'from'=>1,'status'=>0,'resume_id'=>$id])->get();
       if(!empty($msgInfo->toArray())){
           return  response()->json(['code'=>200,'msg'=>'操作成功','data'=>'']);
       }
        $msgId= DB::table('interview_assistant')
            ->insertGetId(['company_id'=>$userInfo->company_id,'send_id'=>$userInfo->id,'receive_id'=>$ownerInfo->id,'type'=>1,'from'=>1,'content'=>'fail','created_at'=>$time,'updated_at'=>$time,'resume_id'=>$id]);
        $content =[
            'data'=>[
                'type'=>2,
                'msgId'=>$msgId,
                'header'=>$resumeInfo->name.'的简历权限申请',
                'info'=>[
                    'name'=>$resumeInfo->name,
                    'img'=>$resumeInfo->image,
                    'position'=>$resumeInfo->position,
                    'cmpName'=>$resumeInfo->company_name,
                    'stepName'=>$resumeInfo->step_name,
                    'applyName'=>$userInfo->name,
                    'jobDate'=>$resumeInfo->job_date,
                    'applyTime'=>$time,
                    'resumeId'=>$id,
                    'applyId'=>$userInfo->id,
                    'msgId'=>$msgId
                ]
            ]
        ];
        $pushContent = $userInfo->name.'申请'.$resumeInfo->name.'的简历';
        $result = $p->sendMsg($from,0,$to,'100',$content,array("push"=>true,"roam"=>true,"history"=>true,"sendersync"=>true, "route"=>false,'needPushNick'=>true),$pushContent);
        if($result['code'] == 200){
            DB::table('interview_assistant')
                ->where('id',$msgId)
                ->update(['content'=>json_encode($content),'updated_at'=>$time]);
            return  response()->json(['code'=>200,'msg'=>'操作成功','data'=>'']);
        }else{
            return  response()->json(['code'=>400,'msg'=>'操作失败','data'=>'']);
        }
    }
    /**
     * 切换简历所有人
     * @param  $id  [简历ID]
     * @param  $reasion    [理由]
     * @return $请求返回结果(json)
     */
    public function applyAction(Request $request){
        $userInfo = $this->user;
        $applyId = $request->input('applyId');
        $msgId = $request->input('msgId');
        $resumesId = $request->input('resumesId');
        $type = $request->input('type');
        $reasion = $request->input('reasion') ?? "";
        $msgInfo = DB::table('interview_assistant')->where('id',$msgId)->first();
        $content = json_decode($msgInfo->content,true);
        $applyInfo = DB::table('users')->where('id',$applyId)->first();
        $resumeInfo = DB::table('resumes')->where(['id'=>$resumesId,'status'=>0])->first();
        if(empty($resumeInfo)){
            return  response()->json(['code'=>400,'msg'=>'该简历已被删除','data'=>'']);
        }
        $from = 'momevipinterview';
        $to = $applyInfo->accid;
        $p = $this->initialize();
        $time = time();
        if($type ==1){
            $res = '同意了';
        }else{
            $res = '拒绝了';
        }
        $pushContent = $userInfo->name.$res.$resumeInfo->name.'的简历申请';
        $result = $p->sendMsg($from,0,$to,'100',$content,array("push"=>true,"roam"=>true,"history"=>true,"sendersync"=>true, "route"=>false,'needPushNick'=>true),$pushContent);
        if($result['code'] == 200){
            if($type==1){
                $get_status = DB::select('select id from resumes where id=? and step_id>=1 and (ask_status!=2||ask_status=0) and (check_status=0||check_status=3) and status=0 limit 1', [$resumesId]);
                $check_resume_status = DB::table('resumes')->where(['status' => 0, 'id' => $resumesId, 'ask_status' => 1, 'check_status' => 1])->first();
                if(!empty($get_status)){
                    return  response()->json(['code'=>400,'msg'=>'该简历已启动流程','data'=>'']);
                }
                if(!empty($check_resume_status)){
                    return  response()->json(['code'=>400,'msg'=>'该候选人已入职','data'=>'']);
                }
                if($resumeInfo->owner_id == $userInfo->id){
                    DB::table('resumes')
                        ->where('id',$resumesId)
                        ->update(['owner_id'=>$applyInfo->id,'updated_at'=>$time]);
                }else{
                    return  response()->json(['code'=>400,'msg'=>'没有权限','data'=>'']);
                }
            }
            DB::table('interview_assistant')
                ->where('id',$msgId)
                ->update(['status'=>$type,'reasion'=>$reasion,'updated_at'=>$time]);
            DB::table('interview_assistant')
                ->insert(['company_id'=>$userInfo->company_id,'send_id'=>$userInfo->company_id,'receive_id'=>$applyInfo->id,'type'=>2,'from'=>1,'status'=>$type,'reasion'=>$reasion,'content'=>json_encode($content),'created_at'=>$time,'updated_at'=>$time]);
            return  response()->json(['code'=>200,'msg'=>'操作成功','data'=>'']);
        }else{
            return  response()->json(['code'=>400,'msg'=>'操作失败','data'=>'']);
        }
    }
    /**
     * 系统消息历史
     * @param $page 分页
     * @return $请求返回结果(json)
     */
    public function systemHistoryMsg(Request $request){
        $userInfo = $this->user;
        $page = $request->input('page') ? $request->input('page') : 1;
        $pageNum = $request->input('perPage') ? $request->input('perPage') : 2;
        $skip = ($page - 1) * $pageNum;
        $take = $pageNum;
        $result = DB::table('system_msg')
            ->join('staff','staff.company_id','=','system_msg.company_id')
            ->where(['staff.mobile'=>$userInfo->mobile,'staff.status'=>0])
            ->whereNotIn('staff.user_id',[0])
            ->select('system_msg.content','system_msg.created_at as time')
            ->skip($skip)
            ->take($take)
            ->orderBy('time','desc')
            ->get();
        if(count($result->toArray())==1){
            foreach($result as $item=>$v){
                $result[$item]->content = json_decode($v->content,true);
            }
            $info = $result;
        }else{
            $info[] =[];
            foreach($result as $item=>$v){
                $info[$item]['content'] = json_decode($v->content,true);
                $info[$item]['time'] = $v->time;
            }
//            $i=1;
//            foreach($result as $item=>$v){
//                $info[$i]['content'] = json_decode($v->content,true);
//                $info[$i]['time'] = $v->time;
//                $i--;
//            }
        }
        if(empty($result->toArray())){
            $info = [];
        }
        return  response()->json(['code'=>200,'msg'=>'操作成功','data'=>$info]);
    }
    /**
     * 面试小助手历史
     * @param  $id  [简历ID]
     * @param  $reasion    [理由]
     * @return $请求返回结果(json)
     */
    public function historyInterview(Request $request){
        $userInfo = $this->user;
        $page = $request->input('page') ? $request->input('page') : 1;
        $pageNum = $request->input('perPage') ? $request->input('perPage') : 2;
        $skip = ($page - 1) * $pageNum;
        $take = $pageNum;
        $result = DB::table('interview_assistant')
            ->select('id','content','from','type','status','updated_at as time')
            ->where(['receive_id'=>$userInfo->id])
            ->whereIn('type',[1,2,3,4])
            ->skip($skip)
            ->take($take)
            ->orderBy('time','desc')
            ->get();
        if(count($result->toArray())==1){
            foreach($result as $item=>$v){
                $content = json_decode($v->content,true);
                $info[0]['time'] = $v->time;
               if($v->from == 1 ){
                   if($v->type==2){
                       switch($v->status){
                           case '1':
                               $header = $content['data']['info']['name'].'的简历权限申请';
                               $title = $content['data']['info']['name'].'的简历权限申请已被同意';
                               break;
                           case '2':
                               $header = $content['data']['info']['name'].'的简历权限申请';
                               $title = $content['data']['info']['name'].'的简历权限申请已被拒绝';
                               break;
                           default :
                               $header = $content['data']['info']['name'].'的简历权限申请';
                               $title = $content['data']['info']['applyName'].'已申请'.$content['data']['info']['name'].'的简历权限，请您尽快处理';
                               break;
                       }
                   }else{
                       $header = $content['data']['info']['name'].'的简历权限申请';
                       $title = $content['data']['info']['applyName'].'已申请'.$content['data']['info']['name'].'的简历权限，请您尽快处理';
                   }
               }else{
                   if($v->type==4){
                       switch($v->status){
                           case '1':
                               $header = $content['data']['info']['name'].'的面试通知';
                               $title = $content['data']['info']['intervierName'].'同意参加'.$content['data']['info']['name'].'的'.$content['data']['info']['stepName'];
                               break;
                           case '2':
                               $header = $content['data']['info']['name'].'的面试通知';
                               $title = $content['data']['info']['intervierName'].'拒绝参加'.$content['data']['info']['name'].'的'.$content['data']['info']['stepName'];
                               break;
                           default :
                               $header = $content['data']['info']['name'].'的面试通知';
                               $hr = DB::table('users')->where('id',$content['data']['info']['hrId'])->first();
                               $title = 'HR'.$hr->name.'邀请您于'.date('Y/m/d日',$content['data']['info']['stime']).'参加'.$content['data']['info']['name'].'的'.$content['data']['info']['stepName'];
                               break;
                       }
                   }else{
                       $header = $content['data']['info']['name'].'的面试通知';
                       $hr = DB::table('users')->where('id',$content['data']['info']['hrId'])->first();
                       $title = 'HR'.$hr->name.'邀请您于'.date('Y/m/d日',$content['data']['info']['stime']).'参加'.$content['data']['info']['name'].'的'.$content['data']['info']['stepName'];
                   }
               }
               $info[0]['from'] = $v->type;
               $info[0]['img'] = $content['data']['info']['img'];
               $info[0]['type'] = $v->status;
               $info[0]['header'] =  $header;
               $info[0]['title'] =  $title;
               $info[0]['id']  = $v->id;
             }
        }else{
            $info[] =[];
            $i=0;
            foreach($result as $item=>$v){
                $content = json_decode($v->content,true);
                $info[$i]['time'] = $v->time;
                if($v->from == 1 ){
                    if($v->type==2){
                        switch($v->status){
                            case '1':
                                $header = $content['data']['info']['name'].'的简历权限申请';
                                $title = $content['data']['info']['name'].'的简历权限申请已被同意';
                                break;
                            case '2':
                                $header = $content['data']['info']['name'].'的简历权限申请';
                                $title = $content['data']['info']['name'].'的简历权限申请已被拒绝';
                                break;
                            default :
                                $header = $content['data']['info']['name'].'的简历权限申请';
                                $title = $content['data']['info']['applyName'].'已申请'.$content['data']['info']['name'].'的简历权限，请您尽快处理';
                                break;
                        }
                    }else{
                        $header = $content['data']['info']['name'].'的简历权限申请';
                        $title = $content['data']['info']['applyName'].'已申请'.$content['data']['info']['name'].'的简历权限，请您尽快处理';
                    }
        
                }else{
                    if($v->type==4){
                        switch($v->status){
                            case '1':
                                $header = $content['data']['info']['name'].'的面试通知';
                                $title = $content['data']['info']['intervierName'].'同意参加'.$content['data']['info']['name'].'的'.$content['data']['info']['stepName'];
                                break;
                            case '2':
                                $header = $content['data']['info']['name'].'的面试通知';
                                $title = $content['data']['info']['intervierName'].'拒绝参加'.$content['data']['info']['name'].'的'.$content['data']['info']['stepName'];
                                break;
                            default :
                                $header = $content['data']['info']['name'].'的面试通知';
                                $hr = DB::table('users')->where('id',$content['data']['info']['hrId'])->first();
                                $title = 'HR'.$hr->name.'邀请您于'.date('Y/m/d日',$content['data']['info']['stime']).'参加'.$content['data']['info']['name'].'的'.$content['data']['info']['stepName'];
                                break;
                        }
                    }else{
                        $header = $content['data']['info']['name'].'的面试通知';
                        $hr = DB::table('users')->where('id',$content['data']['info']['hrId'])->first();
                        $title = 'HR'.$hr->name.'邀请您于'.date('Y/m/d日',$content['data']['info']['stime']).'参加'.$content['data']['info']['name'].'的'.$content['data']['info']['stepName'];
                    }
                }
                $info[$i]['from'] = $v->type;
                $info[$i]['img'] = $content['data']['info']['img'];
                $info[$i]['header'] =  $header;
                $info[$i]['title'] =  $title;
                $info[$i]['id']  = $v->id;
                $info[$i]['type'] = $v->status;
                $i++;
            }
        }
        if(empty($result->toArray())){
            $info = [];
        }
        return  response()->json(['code'=>200,'msg'=>'操作成功','data'=>$info]);
    }
    /**
     * 面试小助手详情
     * @param  $id  [简历ID]
     * @param  $reasion    [理由]
     * @return $请求返回结果(json)
     */
    public function interviewInfo(Request $request){
        $id = $request->input('id');
        $info = DB::table('interview_assistant')
            ->where('id',$id)
            ->select('id','content','from','type','status','reasion')
            ->first();
        $result['content'] =  json_decode($info->content,true)['data']['info'];
        $resumeInfo = DB::table('resumes')->where(['id'=>$result['content']['resumeId']])->first();
//        if(empty($resumeInfo)){
//            return  response()->json(['code'=>400,'msg'=>'该简历已被删除','data'=>'']);
//        }
        $result['content']['stepName'] = $resumeInfo->step_name;
        $result['content']['from'] = $info->from;
        $result['content']['status'] = $info->status;
        $result['content']['reasion'] = $info->reasion;
        return  response()->json(['code'=>200,'msg'=>'操作成功','data'=>$result]);
    }

  
    //群历史消息
    public function historyMsg(Request $request){
        $tid = $request->input('id');
        $teamInfo = DB::table('team')->where('team_id',$tid)->first();
//        dd($resumeInfo);
        $p = $this->initialize();
//        $info=['momevipmsg','momevipinterview','b061dca9989e2f92625d7602d7ad0340','e6e1f5b6e11433f3a7ce18ee431a1f5a','9e25c99f75b509c4d9718a994ca4f3f6'];
//        print_r($p->updateUinfo('momevipinterview','面试小助手','https://test.api.momeyun.com/image/all.png'));
//       print_r($p->getUinfos($info));
//        $accid = md5('15001105304');
//        print_r( $p->createUserId($accid,'15001105304','{}','https://test.api.momeyun.com/image/all.png','') ) ;
//        print_r( $p->createUserId('momevipinterview','面试小助手','{}','https://test.api.momeyun.com/image/all.png','') ) ;
        
//        $tid =  $resumeInfo->team_id;
        $accInfo = DB::table('team_member')->where(['team_id'=>$tid,'is_owner'=>1])->first();
        $accid = $accInfo->acc_id;
        $begintime = $teamInfo->created_at;
        $endTime =microtime(true)*10000;
        $result = $p->queryGroupMsg($tid,$accid,$begintime,$endTime);
        dd($result);
//        dd();
    }
    /**
     * 系统消息编辑
     * @param  $id   [消息ID]
     * @param  $from    [来源]
     *  @param  $title    [标题]
     * @param  $content    [内容]
     * @param  $img    [图片地址]
     * @return $请求返回结果(json)
     */
    public function msgEditor(Request $request){
        $userInfo = $this->user;
        $from =  $request->input('from');
        $id = $request->input('id');
        $title = $request->input('title') ?? "";
        $content = $request->input('content') ?? "";
        $img = $request->input('img') ?? "";
        $time = time();
        switch($from){
            case 1:
                if(empty($id)){
                    $id = DB::table('systemsg_create')->insertGetId(['user_id'=>$userInfo->id,'company_id'=>$userInfo->company_id,'name'=>$userInfo->name,'title_one'=>$title,'imgurl_one'=>$img,'content_one'=>$content,'created_at'=>$time,'updated_at'=>$time]);
                }else{
                    DB::table('systemsg_create')->where('id',$id)->update(['user_id'=>$userInfo->id,'name'=>$userInfo->name,'title_one'=>$title,'imgurl_one'=>$img,'content_one'=>$content,'updated_at'=>$time]);
                }
            break;
            case 2:
                DB::table('systemsg_create')
                    ->where('id',$id)
                    ->update(['title_two'=>$title,'content_two'=>$content,'imgurl_two'=>$img,'updated_at'=>$time]);
            break;
            case 3:
                DB::table('systemsg_create')
                    ->where('id',$id)
                    ->update(['title_three'=>$title,'content_three'=>$content,'imgurl_three'=>$img,'updated_at'=>$time]);
                break;
            case 4:
                DB::table('systemsg_create')
                    ->where('id',$id)
                    ->update(['title_four'=>$title,'content_four'=>$content,'imgurl_four'=>$img,'updated_at'=>$time]);
                break;
        }
        return  response()->json(['code'=>200,'msg'=>'操作成功','data'=>['id'=>$id]]);
    }
    /**
     * 系统消息删除
     * @param  $id   [标题]
     * @param $type [序号]
     * @return $请求返回结果(json)
     */
    public function delMsg(Request $request){
        $id = $request->input('id');
        $type = $request->input('type');
        $userInfo = $this->user;
        $msgInfo = DB::table('systemsg_create')->where('id',$id)->first();
        $time = time();
        $titleTwo = $msgInfo->title_three;
        $titleThree = $msgInfo->title_four;
        $titleFour = '';
        $contentTwo = $msgInfo->content_three;
        $contentThree = $msgInfo->content_four;
        $contentFour = '';
        $imgTwo = $msgInfo->imgurl_three;
        $imgThree = $msgInfo->imgurl_four;
        $imgFour = '';
        switch($type){
            case 2:
                $result = DB::table('systemsg_create')
                    ->where('id',$id)
                    ->update(['title_two'=>$titleTwo,'imgurl_two'=>$imgTwo,'content_two'=>$contentTwo,
                        'title_three'=>$titleThree,'imgurl_three'=>$imgThree,'content_three'=>$contentThree,
                        'title_four'=>$titleFour,'imgurl_four'=>$imgFour,'content_four'=>$contentFour,'updated_at'=>$time]);
                break;
            case 3:
                $result = DB::table('systemsg_create')
                    ->where('id',$id)
                    ->update(['title_three'=>$titleThree,'imgurl_three'=>$imgThree,'content_three'=>$contentThree,
                        'title_four'=>$titleFour,'imgurl_four'=>$imgFour,'content_four'=>$contentFour,'updated_at'=>$time]);
                break;
            case 4:
                $result = DB::table('systemsg_create')
                    ->where('id',$id)
                    ->update([
                        'title_four'=>$titleFour,'imgurl_four'=>$imgFour,'content_four'=>$contentFour,'updated_at'=>$time]);
                break;
            default:
                $result = '';
        }
        if($result){
            return  response()->json(['code'=>200,'msg'=>'操作成功','data'=>['id'=>$id]]);
        }else{
            return  response()->json(['code'=>400,'msg'=>'操作失败','data'=>['id'=>$id]]);
        }
        
    }
    
    /**
     * 系统消息详情
     * @param  $title   [标题]
     * @param  $content    [正文]
     * @param  $tname    [图片]
     * @return $请求返回结果(json)
     */
    public function msgInfo(Request $request){
        $id = $request->input('id');
        $result = DB::table('systemsg_create')
            ->where('id',$id)
            ->select('id','name','updated_at','title_one as titleOne','title_two as titleTwo','title_three as titleThree','title_four as titleFour','content_one as contentOne','content_two as contentTwo','content_three as contentThree','content_four as contentFour','imgurl_one as imgOne','imgurl_two as imgTwo','imgurl_three as imgThree','imgurl_four as imgFour')
            ->first();
        return  response()->json(['code'=>200,'msg'=>'操作成功','data'=>['info'=>$result]]);
    }
    /**
     * 添加系统消息
     * @param  $title   [标题]
     * @param  $content    [正文]
     * @param  $tname    [图片]
     * @return $请求返回结果(json)
     */
    public function addSystemMsg(Request $request){
//        $userInfo = \Auth::guard('api')->user();
        $id = $request->input('id');
        $titleOne = $request->input('titleOne') ?? "";
        $titleTwo = $request->input('titleTwo') ?? "";
        $titleThree = $request->input('titleThree') ?? "";
        $titleFour = $request->input('titleFour') ?? "";
        $contentOne = $request->input('contentOne') ?? "";
        $contentTwo = $request->input('contentTwo') ?? "";
        $contentThree = $request->input('contentThree') ?? "";
        $contentFour = $request->input('contentFour') ?? "";
        $contenturlOne = $request->input('contenturlOne') ?? "";
        $contenturlTwo = $request->input('contenturlTwo') ?? "";
        $contenturlThree = $request->input('contenturlThree') ?? "";
        $contenturlFour = $request->input('contenturlFour') ?? "";
        $result = DB::table('systemsg_create')->where('id',$id)->update([
               'title_one'=>$titleOne,
                'title_two'=>$titleTwo,
                'title_three'=>$titleThree,
                'title_four'=>$titleFour,
                'content_one'=>$contentOne,
                'content_two'=>$contentTwo,
                'content_three'=>$contentThree,
                'content_four'=>$contentFour,
                'content_oneurl'=>$contenturlOne,
                'content_twourl'=>$contenturlTwo,
                'content_threeurl'=>$contenturlThree,
                'content_foururl'=>$contenturlFour,
                'updated_at'=>time()
        ]);
        if(!$result){
            return  response()->json(['code'=>400,'msg'=>'系统消息创建失败','data'=>'']);
        }
        return  response()->json(['code'=>200,'msg'=>'系统消息创建成功','data'=>'']);
    }
    /**
     *  创建的系统消息列表
     * @param  $page     [图片名]
     * @return $请求返回结果(json)
     */
    public function systemMsgList(Request $request){
        $userInfo = $this->user;
        $name = $request->input('name') ?? '';
        $page = $this->page($request);
        if(empty($name) && $name !=0){
            $list = DB::table('systemsg_create')
                ->where([['company_id','=',$userInfo->company_id],['status','=','0']])
                ->select( 'id','name','status','title_one as title','created_at as time')
                ->skip($page['skip'])
                ->take($page['take'])
                ->orderBy('id','desc')
                ->get();
            $count = DB::table('systemsg_create')
                ->where([['company_id','=',$userInfo->company_id],['status','=','0']])
                ->count();
            $sum = ceil($count/$page['take']);
        }else{
            $name = '%'.$name.'%';
            $list = DB::table('systemsg_create')
                ->where([['company_id','=',$userInfo->company_id],['status','=','0'],['title_one','like',$name]])
                ->orWhere([['company_id','=',$userInfo->company_id],['status','=','0'],['name','like',$name]])
                ->select( 'name','id','title_one as title','created_at as time')
                ->skip($page['skip'])
                ->take($page['take'])
                ->orderBy('id','desc')
                ->get();
           $count =  DB::table('systemsg_create')
                ->where([['company_id','=',$userInfo->company_id],['status','=','0'],['title_one','like',$name]])
                ->orWhere([['company_id','=',$userInfo->company_id],['status','=','0'],['name','like',$name]])
               ->count();
            $sum = ceil($count/$page['take']);
        }
        if(!empty($list->toArray())){
            $type = 1;
        }else{
            $type  = 0;
        }
        foreach($list as $item=>$v){
            $sendInfo = DB::table('system_msg')->where('msg_id',$v->id)->count();
            if($sendInfo == 0){
                $v->status=1;
            }else{
                $v->status=0;
            }
        }
        return  response()->json(['code'=>200,'msg'=>'成功','data'=>['list'=>$list,'type'=>$type,'count'=>$count,'sum'=>$sum]]);
    }
    /**
     *  系统消息删除
     * @param  $obj     [序号]
     * @return $请求返回结果(json)
     */
    public function removeSystemsg(Request $request){
        $obj =$request->input('obj');
        if(count($obj) == 0){
            return  response()->json(['code'=>400,'msg'=>'没有可供删除的消息','data'=>'']);
        }
        try{
            foreach($obj as $item){
                DB::table('systemsg_create')->where('id',$item)->update(['status'=>'1']);
            }
        }catch(\Exception $e){
            return  response()->json(['code'=>400,'msg'=>'删除失败','data'=>'']);
        }
        return  response()->json(['code'=>200,'msg'=>'操作成功','data'=>'']);
    }

    /**
     *  素材库图片上传
     * @param  $file     [图片名]
     * @return $请求返回结果(json)
     */
    public function material(Request $request){
        $userInfo = $this->user;
        $type = $request->input('type');
        $count = DB::table('material_library')->where([['company_id',$userInfo->company_id],['status','0']])->count();
        if($count >= 100){
            return  response()->json(['code'=>400,'msg'=>'最多保存100张图片','data'=>'']);
        }
       $uploadImgInfo = $this->upload($request);
        $time = time();
        if($uploadImgInfo['code'] == 200){
           $result =  DB::table('material_library')->insertGetId(
                ['user_id'=>$userInfo->id,
                'company_id'=>$userInfo->company_id,
                'old_name'=>$uploadImgInfo['data']['oldName'],
                'new_name'=>$uploadImgInfo['data']['newName'],
                'url'=>$uploadImgInfo['data']['imgUrl'],
                 'type'=>$type,
                 'created_at'=>$time,
                'updated_at'=>$time]);
           if($result){
               $data =['id'=>$result,'name'=>$uploadImgInfo['data']['oldName'],'imgUrl'=>$uploadImgInfo['data']['imgUrl'],'time'=>$time];
               return  response()->json(['code'=>200,'msg'=>'图片上传成功','data'=>$data]);
           }else{
               return  response()->json(['code'=>400,'msg'=>'图片上传失败','data'=>'']);
           }
        }else{
            return $uploadImgInfo;
        }
    }
    /**
     *  素材库图片删除
     * @param  $obj     [序号]
     * @return $请求返回结果(json)
     */
    public function removeImg(Request $request){
        $obj =$request->input('obj');
        if(count($obj) == 0){
            return  response()->json(['code'=>400,'msg'=>'没有可供删除的图片','data'=>'']);
        }
        try{
            foreach($obj as $item){
                DB::table('material_library')->where('id',$item)->update(['status'=>'1']);
            }
        }catch(\Exception $e){
            return  response()->json(['code'=>400,'msg'=>'删除失败','data'=>'']);
        }
        return  response()->json(['code'=>200,'msg'=>'操作成功','data'=>'']);
    }
    /**
     *  素材库列表
     
     * @return $请求返回结果(json)
     */
    public function materialList(Request $request){
        $userInfo = $this->user;
        $type = $request->input('type') ;
        $page = $this->page($request);
        if(empty($type)){
            $list = DB::table('material_library')
                ->where([['company_id','=',$userInfo->company_id],['status','=','0']])
                ->select( 'id','old_name as name', 'url','type','created_at as time')
                ->skip($page['skip'])
                ->take($page['take'])
                ->orderBy('id','desc')
                ->get();
            $count = DB::table('material_library')
                ->where([['company_id','=',$userInfo->company_id],['status','=','0']])
                ->count();
        }else if($type == 1){
            $list = DB::table('material_library')
                ->where([['company_id','=',$userInfo->company_id],['status','=','0'],['type','=',1]])
                ->select( 'id','old_name as name', 'url','type','created_at as time')
                ->skip($page['skip'])
                ->take($page['take'])
                ->orderBy('id','desc')
                ->get();
            $count = DB::table('material_library')
                ->where([['company_id','=',$userInfo->company_id],['status','=','0'],['type','=',1]])
                ->count();
        }else if($type ==2){
            $list = DB::table('material_library')
                ->where([['company_id','=',$userInfo->company_id],['status','=','0'],['type','=',2]])
                ->select( 'id','old_name as name', 'url','type','created_at as time')
                ->skip($page['skip'])
                ->take($page['take'])
                ->orderBy('id','desc')
                ->get();
            $count = DB::table('material_library')
                ->where([['company_id','=',$userInfo->company_id],['status','=','0'],['type','=',2]])
                ->count();
        }else if($type==3){
            $list = DB::table('material_library')
                ->where([['company_id','=',$userInfo->company_id],['status','=','0'],['type','=',3]])
                ->select( 'id','old_name as name', 'url','type','created_at as time')
                ->skip($page['skip'])
                ->take($page['take'])
                ->orderBy('id','desc')
                ->get();
            $count = DB::table('material_library')
                ->where([['company_id','=',$userInfo->company_id],['status','=','0'],['type','=',3]])
                ->count();
        }
        $sum = ceil($count/$page['take']);
        if(!empty($list->toArray())){
            $type = 1;
        }else{
            $type  = 0;
        }
        return  response()->json(['code'=>200,'msg'=>'成功','data'=>['list'=>$list,'type'=>$type,'count'=>$count,'sum'=>$sum]]);
    }
    /**
     *  系统消息发送
     * @param  $obj     消息列表
     * @return $请求返回结果(json)
     */
    public function sendSystemMsg(Request $request){
        $obj = $request->input('obj');
        $userInfo = $this->user;
        $cmpInfo = DB::table('companies')->where('id',$userInfo->company_id)->first();
        $time = time();
        $from = 'momevipmsg';
        $toInfo = DB::table('staff')
                ->join('users','staff.user_id','=','users.id')
                ->where(['staff.company_id'=>$userInfo->company_id,'staff.status'=>0])
                ->whereNotIn('staff.user_id',[0])
                ->select('users.accid')
                ->get();
        foreach($toInfo as $item){
            $to[] = $item->accid;
        }
        foreach($obj as $k){
           $msgInfo =  DB::table('systemsg_create')->where('id',$k)->first();
            $p = $this->initialize();
            $info = [];
            if(!empty($msgInfo->imgurl_two)){
                $info[] = ['title'=>$msgInfo->title_two,'img'=>$msgInfo->imgurl_two];
            }
            if(!empty($msgInfo->imgurl_three)){
                $info[] = ['title'=>$msgInfo->title_three,'img'=>$msgInfo->imgurl_three];
            }
            if(!empty($msgInfo->imgurl_four)){
                $info[] =  ['title'=>$msgInfo->title_four,'img'=>$msgInfo->imgurl_four];
            }
            $content = [
                'data'=>[
                    'type'=>1,
                    'header'=>['title'=>$msgInfo->title_one,'img'=>$msgInfo->imgurl_one],
                    'id'=>$msgInfo->id,
                    'info'=>$info,
                ]
            ];
            $pushContent = $msgInfo->title_one;
            $result = $p->sendBatchMsg($from,$to,'100',$content,array("push"=>true,"roam"=>true,"history"=>true,"sendersync"=>true, "route"=>false,'needPushNick'=>true),$pushContent);
            if($result['code']==200){
                DB::table('system_msg')->insert(['company_id'=>$userInfo->company_id,'send_id'=>$userInfo->id,'msg_id'=>$msgInfo->id,'content'=>json_encode($content,JSON_UNESCAPED_SLASHES),'created_at'=>$time,'updated_at'=>$time]);
            }else{
                Log::info(date('Y-m-d H:i:s').'系统消息发送失败 '.json_encode($result));
                return  response()->json(['code'=>400,'msg'=>'失败','data'=>'']);
            }
        }
        return  response()->json(['code'=>200,'msg'=>'成功','data'=>'']);
    }
    /**
     *  图片上传
     * @param  $file     [图片名]
     * @return $请求返回结果(json)
     */
    protected function upload(Request $request)
    {
        $file = $request->file('file');
//        dd($file->getClientOriginalName());
        if (!$request->hasFile('file')) {
            $return = ['code'=>400,'msg'=>'上传文件为空或无效','data'=>[]];
            return $return;
        }
        if (!$request->file('file')->isValid()){
            $return = ['code'=>400,'msg'=>$file->getErrorMessage(),'data'=>[]];
            return $return;
        }
        if(!in_array($file->getClientOriginalExtension(),['png','jpg','jpeg'])){
            $return = ['code'=>400,'msg'=>'图片格式不允许','data'=>[]];
            return $return;
        }
        if($file->getClientSize() > $file->getMaxFilesize()){
            $return = ['code'=>400,'msg'=>'图片超过允许2M','data'=>[]];
            return $return;
        }
        if (!empty($file)) {
            $newFileName = md5(time() . rand(0, 10000)) . '.' . $file->getClientOriginalExtension();
            $savePath = 'uploads/' . date('Ym', time());
            $request->file('file')->move($savePath, $newFileName);
            
            $name = $savePath . '/' . $newFileName;
            $return = ['code'=>200,'msg'=>'上传文件成功','data'=>['imgUrl'=>$name,'oldName'=>$file->getClientOriginalName(),'newName'=>$newFileName]];
            return $return;
        }
    }
    //系统消息详情
    public function systemInfo(Request $request){
        $id = $request->input('id');
       $systemInfo =  DB::table('systemsg_create')->where('id',$id)->select('title_one as titleOne','title_two as titlleTwo','title_three as titleThree','title_four as titleFour','content_one as contentOne','content_two as contentTwo','content_three as contentThree','content_four as contentFour' ,'id','imgurl_one as imgOne','imgurl_two as imgTwo','imgurl_three as imgThree','imgurl_four as imgFour')->first();
        return  response()->json(['code'=>200,'msg'=>'操作成功','data'=>['info'=>$systemInfo]]);
    }
    protected function initialize(){
        $config = Config::get('info.yunim');
        $appKey = $config['Appkey'];
        $appSecret = $config['appSecret'];
        $p = new ServerapiController($appKey,$appSecret,'curl');
        return $p;
    }
//    图片上传
    public function img(Request $request){
        $result = $this->upload($request);
        return $result;
    }
}
